package com.darren.archive.route.config;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import org.springframework.core.io.buffer.DataBuffer;
import java.util.logging.Logger;

@Component
public class CustomGlobalFilter implements GlobalFilter, Ordered {

    Logger log = Logger.getLogger(this.getClass().getName());


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
        log.info(exchange.getRequest().getURI().toString());
        if(exchange.getRequest().getRemoteAddress() != null){
            log.info(exchange.getRequest().getRemoteAddress().getHostName());
            log.info(String.valueOf(exchange.getRequest().getRemoteAddress().getAddress()));
            log.info(String.valueOf(exchange.getRequest().getRemoteAddress().getPort()));
            if("0:0:0:0:0:0:0:1".equalsIgnoreCase(exchange.getRequest().getRemoteAddress().getHostName()) || "127.0.0.1".equalsIgnoreCase(exchange.getRequest().getRemoteAddress().getHostName())){
                ServerHttpResponse response = exchange.getResponse();
                response.setStatusCode(HttpStatus.FORBIDDEN);
                byte[] dateBytes = "IP is black".getBytes();
                DataBuffer dataBuffer =  response.bufferFactory().wrap(dateBytes);
                return  response.writeWith(Mono.just(dataBuffer));
            }
        }
        log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        log.info("custom global filter");
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -1;
    }
}